import React, { useRef, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import { Box, Cylinder, Sphere, Line } from '@react-three/drei';
import * as THREE from 'three';

const FormationDrone = ({ 
  drone, 
  showComponents, 
  animationSpeed = 1,
  showTrail = false 
}) => {
  const droneRef = useRef();
  const rotorRefs = useRef([]);
  
  // Animation
  useFrame((state, delta) => {
    // Rotate propellers
    rotorRefs.current.forEach((rotor) => {
      if (rotor) {
        rotor.rotation.y += delta * animationSpeed * 15;
      }
    });
    
    // Update drone position and rotation
    if (droneRef.current) {
      droneRef.current.position.copy(drone.position);
      droneRef.current.rotation.copy(drone.rotation);
    }
  });

  // Rotor positions for quadcopter (smaller than main drone)
  const rotorPositions = useMemo(() => [
    [0.8, 0.05, 0.8],   // Front right
    [-0.8, 0.05, 0.8],  // Front left
    [0.8, 0.05, -0.8],  // Back right
    [-0.8, 0.05, -0.8]  // Back left
  ], []);

  // Trail points for line rendering
  const trailPoints = useMemo(() => {
    if (!showTrail || !drone.trail || drone.trail.length < 2) return [];
    return drone.trail.map(point => [point.x, point.y, point.z]);
  }, [drone.trail, showTrail]);

  return (
    <group ref={droneRef}>
      {/* Trail */}
      {showTrail && trailPoints.length > 1 && (
        <Line
          points={trailPoints}
          color={drone.color}
          lineWidth={2}
          transparent
          opacity={0.6}
        />
      )}
      
      {/* Main Frame (smaller than main drone) */}
      {showComponents.frame && (
        <group>
          {/* Central body */}
          <Box args={[0.5, 0.2, 0.5]} position={[0, 0, 0]}>
            <meshStandardMaterial color={drone.color} />
          </Box>
          
          {/* Arms */}
          <Box args={[1.8, 0.06, 0.06]} position={[0, 0, 0.8]}>
            <meshStandardMaterial color={drone.color} />
          </Box>
          <Box args={[1.8, 0.06, 0.06]} position={[0, 0, -0.8]}>
            <meshStandardMaterial color={drone.color} />
          </Box>
          <Box args={[0.06, 0.06, 1.8]} position={[0.8, 0, 0]}>
            <meshStandardMaterial color={drone.color} />
          </Box>
          <Box args={[0.06, 0.06, 1.8]} position={[-0.8, 0, 0]}>
            <meshStandardMaterial color={drone.color} />
          </Box>
        </group>
      )}

      {/* Rotors and Propellers */}
      {showComponents.rotors && rotorPositions.map((position, index) => (
        <group key={index} position={position}>
          {/* Motor */}
          <Cylinder args={[0.08, 0.08, 0.12]} position={[0, 0, 0]}>
            <meshStandardMaterial color="#34495e" />
          </Cylinder>
          
          {/* Propeller */}
          <group ref={(el) => rotorRefs.current[index] = el}>
            <Box args={[0.015, 0.008, 0.5]} position={[0, 0.07, 0]}>
              <meshStandardMaterial color="#7f8c8d" />
            </Box>
            <Box args={[0.5, 0.008, 0.015]} position={[0, 0.07, 0]}>
              <meshStandardMaterial color="#7f8c8d" />
            </Box>
          </group>
        </group>
      ))}

      {/* Camera (smaller) */}
      {showComponents.camera && (
        <group position={[0, -0.15, 0.2]}>
          <Sphere args={[0.08]} position={[0, 0, 0]}>
            <meshStandardMaterial color="#1a1a1a" />
          </Sphere>
          
          <Cylinder args={[0.04, 0.04, 0.08]} position={[0, 0, 0.08]} rotation={[Math.PI / 2, 0, 0]}>
            <meshStandardMaterial color="#1a1a1a" />
          </Cylinder>
        </group>
      )}

      {/* LED Lights */}
      {showComponents.lights && (
        <group>
          {/* Front light */}
          <Sphere args={[0.015]} position={[0, 0.03, 0.25]}>
            <meshStandardMaterial color="#ffffff" emissive="#ffffff" emissiveIntensity={0.3} />
          </Sphere>
          
          {/* Back light */}
          <Sphere args={[0.015]} position={[0, 0.03, -0.25]}>
            <meshStandardMaterial color={drone.color} emissive={drone.color} emissiveIntensity={0.3} />
          </Sphere>
        </group>
      )}

      {/* Drone ID indicator */}
      <Sphere args={[0.03]} position={[0, 0.15, 0]}>
        <meshStandardMaterial color={drone.color} emissive={drone.color} emissiveIntensity={0.5} />
      </Sphere>
    </group>
  );
};

const DroneFormation = ({ 
  formationState, 
  mainDroneState,
  showComponents,
  animationSpeed = 1,
  showTrails = false
}) => {
  if (!formationState) return null;

  return (
    <group>
      {/* Formation Drones */}
      {formationState.formationDrones.map((drone) => (
        <FormationDrone
          key={drone.id}
          drone={drone}
          showComponents={showComponents}
          animationSpeed={animationSpeed}
          showTrail={showTrails}
        />
      ))}
      
      {/* Formation center indicator (when formation is active) */}
      {formationState.isFormationActive && (
        <group position={formationState.mainDrone.position}>
          <Sphere args={[0.1]} position={[0, -0.5, 0]}>
            <meshStandardMaterial 
              color="#00ff00" 
              transparent 
              opacity={0.3}
              emissive="#00ff00"
              emissiveIntensity={0.2}
            />
          </Sphere>
          
          {/* Formation radius indicator */}
          <mesh rotation={[Math.PI / 2, 0, 0]} position={[0, -0.5, 0]}>
            <ringGeometry args={[formationState.formationRadius - 0.1, formationState.formationRadius + 0.1, 32]} />
            <meshBasicMaterial 
              color="#00ff00" 
              transparent 
              opacity={0.2}
              side={THREE.DoubleSide}
            />
          </mesh>
        </group>
      )}
      
      {/* Program visualization */}
      {formationState.activeProgram && (
        <group position={formationState.mainDrone.position}>
          {/* Program indicator */}
          <Sphere args={[0.15]} position={[0, 2, 0]}>
            <meshStandardMaterial 
              color={formationState.activeProgram === 'orbit' ? '#3498db' : '#e74c3c'}
              transparent 
              opacity={0.6}
              emissive={formationState.activeProgram === 'orbit' ? '#3498db' : '#e74c3c'}
              emissiveIntensity={0.3}
            />
          </Sphere>
          
          {/* Program name text would go here if we had text rendering */}
        </group>
      )}
    </group>
  );
};

export default DroneFormation;
